Page({
  data: {
    stats: {
      totalTodos: 0,
      completedTodos: 0,
      pendingTodos: 0,
      completionRate: 0,
      todayAdded: 0,
      weeklyData: []
    },
    chartData: []
  },

  onLoad() {
    this.calculateStats()
  },

  onShow() {
    this.calculateStats()
  },

  // 计算统计数据
  calculateStats() {
    const todos = wx.getStorageSync('todos') || []
    const today = new Date()
    const todayStr = today.toDateString()
    
    // 基础统计
    const totalTodos = todos.length
    const completedTodos = todos.filter(todo => todo.completed).length
    const pendingTodos = totalTodos - completedTodos
    const completionRate = totalTodos > 0 ? Math.round((completedTodos / totalTodos) * 100) : 0
    
    // 今日新增
    const todayAdded = todos.filter(todo => {
      const todoDate = new Date(todo.createdAt)
      return todoDate.toDateString() === todayStr
    }).length

    // 最近7天数据
    const weeklyData = this.getWeeklyData(todos)
    
    // 图表数据
    const chartData = this.generateChartData(weeklyData)

    this.setData({
      stats: {
        totalTodos,
        completedTodos,
        pendingTodos,
        completionRate,
        todayAdded,
        weeklyData
      },
      chartData
    })
  },

  // 获取最近7天数据
  getWeeklyData(todos) {
    const weeklyData = []
    const today = new Date()
    
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(date.getDate() - i)
      const dateStr = date.toDateString()
      
      const dayTodos = todos.filter(todo => {
        const todoDate = new Date(todo.createdAt)
        return todoDate.toDateString() === dateStr
      })
      
      weeklyData.push({
        date: date.getMonth() + 1 + '/' + date.getDate(),
        added: dayTodos.length,
        completed: dayTodos.filter(todo => todo.completed).length
      })
    }
    
    return weeklyData
  },

  // 生成图表数据
  generateChartData(weeklyData) {
    return weeklyData.map(day => ({
      label: day.date,
      value: day.added,
      completed: day.completed
    }))
  },

  // 清空所有数据
  clearAllData() {
    wx.showModal({
      title: '危险操作',
      content: '确定要清空所有待办事项数据吗？此操作不可恢复！',
      confirmColor: '#ff6b6b',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('todos')
          this.calculateStats()
          
          wx.showToast({
            title: '数据已清空',
            icon: 'success'
          })
        }
      }
    })
  },

  // 格式化日期时间
  formatDateTime(dateInput) {
    if (!dateInput) return ''
    
    try {
      let date
      
      // 处理不同的日期格式
      if (typeof dateInput === 'string') {
        date = new Date(dateInput)
      } else if (dateInput instanceof Date) {
        date = dateInput
      } else if (typeof dateInput === 'number') {
        date = new Date(dateInput)
      } else {
        date = new Date(String(dateInput))
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn('❌ 无效的日期格式:', dateInput)
        return String(dateInput)
      }
      
      // 手动格式化，确保兼容性
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}年${month}月${day}日 ${hours}:${minutes}`
      
    } catch (error) {
      console.error('❌ 格式化日期时间失败:', error, '原始数据:', dateInput)
      return String(dateInput)
    }
  },

  // 导出数据
  exportData() {
    const todos = wx.getStorageSync('todos') || []
    if (todos.length === 0) {
      wx.showToast({
        title: '暂无数据可导出',
        icon: 'none'
      })
      return
    }

    // 生成导出文本
    let exportText = '待办事项导出数据\n'
    exportText += '导出时间：' + this.formatDateTime(new Date()) + '\n\n'
    
    todos.forEach((todo, index) => {
      exportText += `${index + 1}. ${todo.text}\n`
      exportText += `   状态：${todo.completed ? '已完成' : '待完成'}\n`
      exportText += `   创建时间：${this.formatDateTime(new Date(todo.createdAt))}\n\n`
    })

    // 复制到剪贴板
    wx.setClipboardData({
      data: exportText,
      success: () => {
        wx.showToast({
          title: '数据已复制到剪贴板',
          icon: 'success'
        })
      }
    })
  }
})
